package com.java.wx.controller;

import com.java.bean.*;
import com.java.mvc.Body;
import com.java.service.CourierService;
import com.java.service.ExpressService;
import com.java.service.UserService;
import com.java.util.JSONUtil;
import com.java.util.UserUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Stream;

public class ExpressController {

    // 由于排序要全查，耗费资源较大，考虑做缓存
    // 每日更新
    private static Date date = null;
    private static String lazyboard = null;

//    @Body("/express/.do")
//    public String (HttpServletRequest req, HttpServletResponse resp) {

    @Body("/express/getByNumber.do")
    public String getByNumber(HttpServletRequest req, HttpServletResponse resp) {
        String number = req.getParameter("number");
        if (number == null) {
            return new Message(-2, "无法查询信息").toJSON();
        }
        Express express = ExpressService.getExpressByNumber(number);
        if (express == null) {
            return new Message(-1, "未查询到相关信息").toJSON();
        }
        return new Message(0, "查询成功", new BootstrapTableExpress(express)).toJSON();
    }

    @Body("/express/lazyboard.do")
    public String lazyboard(HttpServletRequest req, HttpServletResponse resp) {
        // 获取今天 00:00:00 的日期
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        // 如果没有缓存或上次缓存的时间在昨天则更新缓存
        if (lazyboard == null || date.before(cal.getTime())) {
            Map<String, List<Map<String, Object>>> result = new HashMap<>();
            List<Object[]> all = ExpressService.getAllExpressRankByPhone();
            List<Object[]> year = ExpressService.getYearExpressRankByPhone();
            List<Object[]> month = ExpressService.getMonthExpressRankByPhone();
            result.put("all", organize(all));
            result.put("year", organize(year));
            result.put("month", organize(month));
            date = new Date();
            lazyboard = new Message(0, result).toJSON();
        }
        return lazyboard;
    }

    private List<Map<String, Object>> organize(List<Object[]> data) {
        List<Map<String, Object>> list = new ArrayList<>();
        for (Object[] os : data) {
            Map<String, Object> map = new HashMap<>();
            User user = UserService.getUserByPhone((String) os[1]);
            String name;
            if (user == null) {
                Courier courier = CourierService.getCourierByPhone((String) os[1]);
                name = courier != null ? courier.getName() : "未知用户";
            } else {
                name = user.getName();
            }
            map.put("name", name);
            map.put("score", os[0]);
            list.add(map);
        }
        return list;
    }

    @Body("/express/add.do")
    public String add(HttpServletRequest req, HttpServletResponse resp) {
        return JSONAdd(req);
    }

    public static String JSONAdd(HttpServletRequest req) {
        final String number = req.getParameter("number");
        final String company = req.getParameter("company");
        final String username = req.getParameter("username");
        final String userphone = req.getParameter("userphone");
        final String send = req.getParameter("sendMessage");
        Courier courier = UserUtil.getCourier(req);
        Admin admin = UserUtil.getAdmin(req.getSession());
        String sysphone;
        if (courier == null) {
            if (admin == null) {
                return new Message(-404, "请先登录").toJSON();
            }
            sysphone = admin.getPhone();
        } else {
            sysphone = courier.getPhone();
        }
        if (sysphone == null) {
            return new Message(-2, "无录入人手机号，无法录入！").toJSON();
        }
        final Express express = new Express(number, company, username, userphone, sysphone);
        final boolean flag = ExpressService.insert(express, "true".equals(send)) > 0;
        if (flag) {
            if (courier != null) {
                CourierService.addDispatches(courier.getId());
            }
            return JSONUtil.toJSON(new Message(0, "新增快递成功！"));
        }
        return JSONUtil.toJSON(new Message(-1, "新增快递失败！快递单号重复了？"));
    }

    @Body("/express/updateStatus.do")
    public String updateStatus(HttpServletRequest req, HttpServletResponse resp) {
        return (ExpressService.updateState(req.getParameter("code")) ? new Message(0, "取件成功") : new Message(-1, "取件失败")).toJSON();
    }

    @Body("/express/getExpressByCode.do")
    public String getExpressByCode(HttpServletRequest req, HttpServletResponse resp) {
        String code = req.getParameter("code");
        Express express = ExpressService.getExpressByCode(code);
        if (express != null) {
            return new Message(0, "查询成功", new BootstrapTableExpress(express)).toJSON();
        }
        return new Message(-1, "未查询到相关信息").toJSON();
    }

    @Body("/express/getNotOutExpresses.do")
    public String getNotOutExpresses(HttpServletRequest req, HttpServletResponse resp) {
        String phone = req.getParameter("phone");
        List<Express> list = ExpressService.getExpressByUserphoneAndStatus(phone, 0);
        if (list == null || list.isEmpty()) {
            return new Message(-1, "未查询到信息").toJSON();
        }
        Stream<Express> sorted = list.stream().sorted(Comparator.comparing(Express::getIntime));
        Object[] objects = sorted.toArray();
        List<BootstrapTableExpress> result = new ArrayList<>();
        for (Object object : objects) {
            result.add(new BootstrapTableExpress((Express) object));
        }
        return new Message(0, "查询成功", result).toJSON();
    }

    @Body("/express/getAllExpresses.do")
    public String getAllExpresses(HttpServletRequest req, HttpServletResponse resp) {
        User user = UserUtil.getUser(req);
        String phone;
        if (user != null) {
            phone = user.getPhone();
        } else {
            Courier courier = UserUtil.getCourier(req);
            phone = courier.getPhone();
        }
        if (phone == null) {
            return new Message(-2).toJSON();
        }
        List<Express> list = ExpressService.getExpressByUserphone(phone);
        if (list == null) {
            return new Message(-1).toJSON();
        }
        Stream<Express> s1 = list.stream().filter(o -> o.getEstatus() == 0);
        Stream<Express> s2 = list.stream().filter(o -> o.getEstatus() != 0);
        s1 = s1.sorted(Comparator.comparing(Express::getIntime).reversed());
        s2 = s2.sorted(Comparator.comparing(Express::getIntime).reversed());
        Object[] os1 = s1.toArray();
        Object[] os2 = s2.toArray();
        List<BootstrapTableExpress> notOut = new ArrayList<>();
        List<BootstrapTableExpress> hadOut = new ArrayList<>();
        for (Object o : os1) {
            notOut.add(new BootstrapTableExpress((Express) o));
        }
        for (Object o : os2) {
            hadOut.add(new BootstrapTableExpress((Express) o));
        }
        Map<String, List<BootstrapTableExpress>> map = new HashMap<>();
        map.put("notOut", notOut);
        map.put("hadOut", hadOut);
        return new Message(0, null, map).toJSON();
    }

}
